<script setup>
import { ref } from 'vue'
import axios from "@/utils/request.js";
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted } from "vue";

import { adminSelectByRoleService, adminAddService, adminModifyService,adminDeleteService } from '@/api/admin'
// 分页查询
const teacherInfo = ref([])
const selectIds = Array


const handleSelectionChange = (selection) => {
  selectIds.value = selection.map(item => item.teacherId)
}

//分页查询底部导航栏
const pageNo = ref(1)
const pageSize = ref(10)
const teacherNameInput = ref()
const groupNameInput = ref()
const total = ref(0)

//页面加载的时候发送一次查询请求
onMounted(() => {
  load()
})
const handleCurrentChange = (val) => {
  pageNo.value = val
  load()
}
const handleSizeChange = (val) => {
  pageSize.value = val
  load()
}
//发送分页查询请求（包括搜索功能）
const load = async () => {
  const res = await adminSelectByRoleService(
    pageNo.value, pageSize.value, 2,teacherNameInput.value
  )
  if (res.data.status === 'success') {
    teacherInfo.value = res.data.data.list
    total.value = res.data.data.totalCount
    console.log(teacherInfo.value)
  } else {
    ElMessage.error(res.data.info)
  }
}

/**
 * 添加老师
 */
//定义模态窗口变量和表格对象
const showAddModal = ref(false)
const teacherInfoAddForm = ref({
  userName: '',
  role: 2,
  account: '',
})
//打开模态窗口
const openAddModal = () => {
  //清空对象内容
  teacherInfoAddForm.value = {
    userName: '',
    role: 2,
    account: '',
  }
  showAddModal.value = true
}
//定义校验规则变量
const ruleFormRef = ref()
const ruleFormModifyRef = ref()
const rules = {
  userName: [
    { required: true, message: '老师姓名不能为空', trigger: 'blur' },
  ],
  account: [
    { required: true, message: '账号不能为空', trigger: 'blur' },
    { min: 4, max: 20, message: '账号长度必须为4-20位', trigger: 'blur' }
  ],
}
//发送添加老师请求
const addTeacherInfo = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      const res = await adminAddService(teacherInfoAddForm.value)
      if (res.data.status === 'success') {
        await load()
        ElMessage.success('添加老师账号成功')
      } else {
        ElMessage.error(res.data.info)
      }
      showAddModal.value = false
    }
  })
}

/**
 * 修改老师信息
 * @type {Ref<UnwrapRef<boolean>, UnwrapRef<boolean> | boolean>}
 */
//修改老师（弹出模态窗口）
//定义模态窗口变量和表格对象
const modifyIntroduceModel = ref(false)
const showModifyModal = ref(false)
const teacherForm = ref({
  userName: '',
  role: 2,
  account: '',
})
const openModifyModal = (teacherInfo) => {
  //将老师数据渲染到模态窗口的表格上面
  teacherForm.value.userId = teacherInfo.userId
  teacherForm.value.userName = teacherInfo.userName
  teacherForm.value.role = teacherInfo.role
  teacherForm.value.account = teacherInfo.account
  //打开模态窗口
  showModifyModal.value = true
}

//发送修改老师请求
const handleEdit = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      const res = await adminModifyService(teacherForm.value)
      if (res.data.status === 'success') {
        await load()
        ElMessage.success('修改老师账号信息成功')
      } else {
        ElMessage.error(res.data.info)
      }
      showModifyModal.value = false
    }
  })
}

/**
 * 删除老师
 */
const openDeleteModal = (userId) => {
  ElMessageBox.confirm(
    '确定要删除该老师账号吗?',
    '警告',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      const res = await adminDeleteService(userId)
      if (res.data.status === 'success') {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
      } else {
        ElMessage({
          type: 'error',
          message: res.data.info,
        })
      }
      await load()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

const getToken = () => {
  return localStorage.getItem('token')
}
</script>

<template>
  <!--  模态窗口-->
  <!--  修改成员信息模态窗口-->
  <div class="modify-modal" v-show="showModifyModal">
    <div class="modify-form">
      <div class="close-btn" @click="showModifyModal = false">&times;</div>
      <h1 style="text-align: center;font-size: 30px">修改老师信息</h1>
      <el-form :model="teacherForm" ref="ruleFormModifyRef" :rules="rules" label-width="auto"
        style="max-width: 600px;margin: auto;margin-top: 50px">
        <el-form-item label="老师昵称" prop="userName">
          <el-input v-model="teacherForm.userName" />
        </el-form-item>
        <el-form-item label="账号" prop="account">
          <el-input v-model="teacherForm.account" />
        </el-form-item>
        <el-form-item style="float: right">
          <el-button type="primary" @click="handleEdit(ruleFormModifyRef)">修改</el-button>
          <el-button @click="showModifyModal = false">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 修改老师介绍模态窗口 -->
    <el-dialog v-model="modifyIntroduceModel" fullscreen top="40vh" width="70%" draggable>
      <span>老师介绍</span>
      <template #footer>

        <div class="dialog-footer">
          <el-button @click="modifyIntroduceModel = false">取消</el-button>
          <el-button type="primary" @click="modifyIntroduceModel = false">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  <!--  添加老师模态窗口-->
  <div class="modify-modal" v-show="showAddModal">
    <div class="modify-form">
      <div class="close-btn" @click="showAddModal = false">&times;</div>
      <h1 style="text-align: center;font-size: 30px">添加老师</h1>
      <el-form :model="teacherInfoAddForm" ref="ruleFormRef" :rules="rules" label-width="auto"
        style="max-width: 600px;margin: auto;margin-top: 50px">
        <el-form-item label="老师昵称" prop="userName">
          <el-input v-model="teacherInfoAddForm.userName" />
        </el-form-item>
        <el-form-item label="账号" prop="account">
          <el-input v-model="teacherInfoAddForm.account" />
        </el-form-item>
        <el-form-item style="float: right">
          <el-button type="primary" @click="addTeacherInfo(ruleFormRef)">添加</el-button>
          <el-button @click="showAddModal = false">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 填写老师介绍模态窗口 -->
    <el-dialog v-model="introduceModel" fullscreen top="40vh" width="70%" draggable>
      <span>老师介绍</span>
      <template #footer>
        <div>
          <v-md-editor v-model="teacherInfoAddForm.introduction" height="400px" :include-level="[1, 2, 3, 4]"
            :disabled-menus="[]" @upload-image="handleUploadImage" />
        </div>
        <div class="dialog-footer">
          <el-button @click="introduceModel = false">取消</el-button>
          <el-button type="primary" @click="introduceModel = false">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  <!--    展示题目内容模态窗口-->
  <el-dialog v-model="showIntroduction" title="老师介绍" width="800">

    <div style="height: 500px;">
      <span style="width: 100% !important;display: block;float: left;height: 500px">
        <MdPreview style="border: 1px solid;" :modelValue="currentIntroduction">
        </MdPreview>
        <!-- <v-md-editor :model-value="currentIntroduction" mode="preview" ref="preview"></v-md-editor> -->
      </span>


    </div>
  </el-dialog>

  <div>
    <!--    功能按钮-->
    <el-card style="width: 34%;margin-bottom: 30px;float: left">
      <el-button @click="openAddModal" type="primary">添加老师</el-button>
    </el-card>
    <!--    搜索框-->
    <el-card class="member-search">
      <span style="margin-left: 10px">
        <h2>老师昵称：</h2>
      </span>
      <input v-model="teacherNameInput" @keyup.enter.native="load">
      <el-button type="warning" @click="load">搜索</el-button>
    </el-card>
  </div>
  <div>
    <el-table ref="multipleTableRef" :data="teacherInfo" stripe style="width: 100%;margin-top: 30px"
      @selection-change="handleSelectionChange">
      <el-table-column width="55" />
      <el-table-column property="userId" label="编号" width="300" />
      <el-table-column property="userName" label="老师昵称" width="300" />
      <el-table-column property="account" label="老师账号" width="300" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" type="info" @click="openModifyModal(scope.row)">
            修改
          </el-button>
          <el-button size="small" type="danger" @click="openDeleteModal(scope.row.userId)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--    分页组件-->
    <el-card style="margin-top: 20px;float: right;">
      <div class="demo-pagination-block">
        <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[2, 5, 10, 20]"
          size="large" :background="true" layout="total, sizes, prev, pager, next, jumper" :total="total"
          @current-change="handleCurrentChange" @size-change="handleSizeChange" />
      </div>
    </el-card>

  </div>
</template>


<style scoped>
/*模态窗口样式*/
.modify-modal {
  position: fixed;
  z-index: 10;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: black;
  opacity: .95;
}

/*模态窗口表格样式*/
.modify-form {
  background-color: #ffffff;
  margin: 10% auto;
  /* 15% from the top and centered */
  padding: 20px;
  border: 1px solid #888;
  z-index: 10;
  border-radius: 10%;
  width: 30%;
  /* Could be more or less, depending on screen size */
}

.close-btn {
  cursor: pointer;
  color: #000000;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

/*搜索样式*/
.member-search {
  width: 64%;
  float: right
}

.member-search span {
  float: left;
}

.member-search input {
  float: left;
  height: 25px;
  border: solid 2px;
  margin-top: 2px;
}

/*表头样式*/
:deep() th.el-table__cell {
  color: black;
  font-size: 15px;
}
</style>
